<?php

require_once 'lib/business/main.php';

class Page extends BasePage {
  const REMOVE_PREFIX = 'widget_remove';

  function tinkle($output = '') {
    $error = '';
    if(isset($this->post['widget']) && isset($this->post['user']) && isset($this->post['page'])) {
      // we have some sort of change request
      if(isset($this->post['add']) && filter_var($this->post['add'],FILTER_VALIDATE_BOOLEAN) == true) {
        // add a new widget
        if(file_exists('lib/widgets/'.$this->post['widget'].'.php')) {
          if($this->db->query("INSERT INTO users_widgets (users_id,widget,users_pages_id) VALUES (".((int)$this->post['user']).",'".$this->db->real_escape_string($this->post['widget'])."',".((int)$this->post['page']).")")) {
            // success
            $new_id = $this->db->insert_id;
            echo json_encode(array('data' => rawurlencode('<div class="new">Successfully added</div>'),'id' => "$new_id"));
            return;
          } else {
            // send some error message
            $error .= 'Could not insert new widget for user';
          }
        } else {
          // send back some error message
          $error .= 'Could not find the widget class file: lib/widgets/'.$this->post['widget'].'.php';
        }
      } elseif (strpos($this->post['widget'],$this::REMOVE_PREFIX) !== false && isset($this->post['page'])) {
        // remove an existing widget from this user and page
        $widget_id = substr($this->post['widget'],strlen($this::REMOVE_PREFIX));
        $page = (int)$this->post['page'];
        $user_id = (int)$this->post['user'];
        if($this->db->query("DELETE FROM users_widgets WHERE id = {$widget_id} && users_id = {$user_id} && users_pages_id = ${page}")) {
          error_log("draggable_widgets->delete: "."DELETE FROM users_widgets WHERE id = {$widget_id} && users_id = {$user_id} && users_pages_id = ${page}");
          // send a success message back
          echo '<div class="new">Successfully removed</div>';
          return;
        } else {
          // send some error message back
          $error .= 'Could not delete.';
        }
      } else {
        // should never happen => error
        $error .= "Not enough data: ".print_r($this->post,true);
      }
    } else {
      $error .= 'Not all things sent: '.print_r($this->post,true);
    }
    echo '<div class="failure">'.$error.'</div>';
  }

  function output_callback($output) {
    return $output;
  }
}
?>
